package com.duoec.magichour.core;

import com.duoec.magichour.core.utils.SpringContextHolder;
import com.google.common.base.Strings;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * Created by ycoe on 17/7/5.
 */
public class CommonConst {

    /**
     * Controller执行完preHandle后的时间，用于计算controller所有耗时
     */
    public static final String CONTROLLER_START_TIME = "CONTROLLER_START_TIME";

    /**
     * controller内方法耗时超过此值时，会写个慢响应日志
     */
    public static final int SLOW_CONTROLLER_TIME = 500;

    /**
     * 编码
     */
    public static final String ENCODE = "UTF-8";

    /**
     * FreemarkerVars变量名
     */
    public static final String MAGIC_HOUR_VAR = "MAGIC_HOUR_VAR";

    /**
     * portlet慢响应
     */
    public static final long SLOW_PORTLET_TIME = 500;

    /**
     * 视图是否开启缓存
     */
    public static boolean VIEW_CACHE = false; // NOSONAR

    /**
     * tp_assets.duoec.com静态网站的路径
     */
    public static String TP_ASSETS_PATH;

    public static String TP_ASSETS_URL; // NOSONAR

    /**
     * 静态文件路径(完整路径)
     */
    public static String STATIC_PATH; // NOSONAR

    /**
     * 主域名
     */
    public static String DOMAIN;

    /**
     * 静态文件URL
     */
    public static String STATIC_URL; // NOSONAR

    public static void init() {
        String viewCacheValue = SpringContextHolder.getStringProperty("view.cache");
        VIEW_CACHE = viewCacheValue == null || "true".equalsIgnoreCase(viewCacheValue);

        //未指定静态文件目录时，尝试从上下文环境中获取
        ApplicationContext c = SpringContextHolder.getApplicationContext();
        if (c instanceof XmlWebApplicationContext) {
            //使用jetty启动时
            XmlWebApplicationContext context = (XmlWebApplicationContext) c;
            if (STATIC_PATH == null) {
                STATIC_PATH = context.getServletContext().getRealPath(".");
            }
        } else if (c instanceof GenericApplicationContext) {
            //使用junit启动时
            if (STATIC_PATH == null) {
                STATIC_PATH = System.getProperty("user.dir") + "/src/main/webapp";
            }
        }

        if (!STATIC_PATH.endsWith("/")) {
            STATIC_PATH += "/";
        }

        DOMAIN = SpringContextHolder.getStringProperty("domain.main");
        if (DOMAIN != null && DOMAIN.contains(".dev")) {
            //如果是本地开发环境时
            STATIC_PATH += "static/";
        } else {
            STATIC_PATH += "dist/";
        }

        TP_ASSETS_PATH = SpringContextHolder.getStringProperty("tp_assets.path");
        if (Strings.isNullOrEmpty(TP_ASSETS_PATH)) {
            TP_ASSETS_PATH = STATIC_PATH;
        }
        if (!TP_ASSETS_PATH.endsWith("/")) {
            TP_ASSETS_PATH += "/";
        }

        TP_ASSETS_URL = "";

        STATIC_URL = SpringContextHolder.getStringProperty("static.url");
    }
}
